<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket协议</title>
    <script type="text/javascript">
        window.onload=function (ev) {
            document.getElementById("sendMsgBtn").onclick = function () {
                var requestTarget = document.getElementById("request");
                var message = requestTarget.value;
                if(message==null || message===''){
                    return;
                }
                if(!window.WebSocket){
                    return;
                }
                if(socket.readyState===WebSocket.OPEN){
                    socket.send(message);
                }

            };
            document.getElementById("clearMsgBtn").onclick = function () {
                var response = document.getElementById("response");
                response.value = "";
            }
        };
        var socket;
        if(window.WebSocket){
            socket = new WebSocket("ws://localhost:8899/ws");
            socket.onmessage = function (ev) {
                var target = document.getElementById("response");
                target.value = target.value+"\n"+ev.data;
            };
            socket.onopen = function (ev) {
                var target = document.getElementById("response");
                target.value = "建立连接成功";
            };
            socket.onclose = function (ev) {
                var target = document.getElementById("response");
                target.value = target.value+"\n"+"断开连接";
            };
        }else {
            alert("不支持websocket协议");
        }
    </script>
</head>
<body>
<form onsubmit="return false">
    <textarea name="requestText" id="request" style="width: 400px; height: 200px"></textarea>
    <input type="button" value="发送消息" id="sendMsgBtn">
    <br><br>
    <textarea name="responseText" id="response" style="width: 400px; height: 200px"></textarea>
    <input type="button" value="清空消息" id="clearMsgBtn">
</form>
</body>
</html>